package cn.Y_Qiu.org.controller;

import cn.Y_Qiu.basic.util.Ajaxresult;
import cn.Y_Qiu.basic.util.FastDfsUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {

    @PostMapping
    public Ajaxresult upload(@RequestPart(required = true ,value = "file")MultipartFile multipartFile) {
        try {
            // 获取文件名
            String filename =  multipartFile.getOriginalFilename();
            // 获取后缀名
            String fname = filename.substring(filename.lastIndexOf(".") + 1);
            // 调用util获取路径
            String path = FastDfsUtil.upload(multipartFile.getBytes(), fname);
            // 将path返回给前端存入模型层
            return  Ajaxresult.me().setResultObj(path);
        } catch (IOException e) {
            e.printStackTrace();
            return Ajaxresult.me().setMessage("上传出错");
        }
    }

    @DeleteMapping
    public Ajaxresult delete(@RequestParam(required = true,value = "path")String filePath){
        // 获取用来截取的字符串(去掉0下标"/"出字符)
        String pathtosub = filePath.substring(1);
        // 截取group
        String group = pathtosub.substring(0, pathtosub.indexOf("/"));
        String imgpath = pathtosub.substring(group.indexOf("/") + 1);
        FastDfsUtil.delete(group, imgpath);
        return Ajaxresult.me();
    }


}
